﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using MySql.Data;
using MySql.Data.MySqlClient;
using System.Configuration;
using Microsoft.Win32;

namespace Friesland_Campina_UpdateStock
{
    class Updating
    {
        private MySqlConnection connection;

        public Updating(){ }

        private void openConnection()
        {
            if (connection == null)
            {
                string connStr = ConfigurationManager.AppSettings["Friesland_Campina_CRM_Local"].ToString();
                connection = new MySqlConnection(connStr);
            }
            connection.Open();
        }

        //Cap nhat thong tin so luong san pham tai moi cua hang theo ngay
        public int update(DateTime pCurrDate)
        {
            try
            {
                openConnection();
                string currDatetime = pCurrDate.Date.ToString("yyyy-MM-dd");
                string commandText = " insert into product_in_shop_diary (by_product, by_shop, datetime_diary, quantity, price, price_by_company) "
                                    + " select A.by_product, A.by_shop, '" + currDatetime + "' as datetime_diary, A.quantity, A.price_in_shop as price, A.price_by_company from product_in_shop A "
                                    + " left join "
                                    + " (select * from product_in_shop_diary where datetime_diary = '" + currDatetime + "') B "
                                    + " on A.by_product = B.by_product"
                                    + " where B.datetime_diary is null";
                MySqlCommand command = new MySqlCommand(commandText, connection);
                int result = command.ExecuteNonQuery();
                connection.Close();
                return result;
            }
            catch (Exception ex)
            {
                throw ex;
            }
        }

        //Lay ngay dau tien cua thang
        public DateTime getFirstDayofMonth(DateTime pCurrDatetime)
        {
            return new DateTime(pCurrDatetime.Year, pCurrDatetime.Month, 1);
        }

        //Lay ngay cuoi cung cua thang
        public DateTime getLastDayofMonth(DateTime pCurrDatetime)
        {
            DateTime temp = getFirstDayofMonth(pCurrDatetime);
            return temp.AddMonths(1).AddDays(-1);
        }
    }
}
